import logging
import hashlib
import os
from google.appengine.api import namespace_manager
from datetime import datetime
from ovzdusi_util import CacheManager
from ovzdusi_generateentities import GenerateMeasurePoint
from google.appengine.api import memcache
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util, template


class MainHandler(webapp.RequestHandler):
    def get(self):
        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, None))

class DataWeekHandler(webapp.RequestHandler):
    def get(self):
        data = CacheManager().getWeekData()

        self.response.headers["Content-Type"] = "application/x-javascript"
        self.response.headers["Cache-Control"] = "max-age=3960"
        etag = hashlib.sha1(data).hexdigest()
        self.response.headers.add_header("Etag", etag)

        self.response.out.write(data)

class DataMonthHandler(webapp.RequestHandler):
    def get(self):
        data = CacheManager().getMonthData()

        self.response.headers["Content-Type"] = "application/x-javascript"
        self.response.headers["Cache-Control"] = "max-age=21600"
        etag = hashlib.sha1(data).hexdigest()
        self.response.headers.add_header("Etag", etag)

        self.response.out.write(data)

class DataMonthTaskHandler(webapp.RequestHandler):
    def get(self):
        cache = CacheManager()
        data = cache.getMonthDataObj()
        result = cache.prepareDataStr(data, "_data_month", "_start_date_month").encode('utf-8')
        memcache.add(cache.CACHE_KEY_MONTHDATA_STR, result)


def main():
    #logging.getLogger().setLevel(logging.CRITICAL)
    application = webapp.WSGIApplication([
        ('/dataweek.js', DataWeekHandler),
        ('/datamonth.js', DataMonthHandler),
        ('/tasks/datamonth', DataMonthTaskHandler),
        ('/', MainHandler),
        ], debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
